﻿$(function () {
    $("#RoleEditDialog").dialog({
        autoOpen: false,
        show: "fade",//fix ie bug
        hide: "fade",
        modal: true,
        height: 350,
        width: 600,
        open: function (event, ui) {
            $('.ui-dialog-titlebar', ui.dialog || ui).hide();
        }
    });
    $("#UserListDialog").dialog({
        autoOpen: false,
        show: "fade",//fix ie bug
        hide: "fade",
        modal: true,
        height: 250,
        width: 400,
        open: function (event, ui) {
            $('.ui-dialog-titlebar', ui.dialog || ui).hide();
        }
    });
    // User Model
    var User = Backbone.Model.extend({
        idAttribute: "UserName",
        initialize: function () {
        },
        defaults: {
            UserName: '',
            RoleName: '',
            IsInRole: false
        }
    });
    // Role Model
    var Role = Backbone.Model.extend({
        url: '/',//fix ie bug
        idAttribute: "RoleName",
        isNew: function () {
            if (this.id == '') {
                return true;
            }
            return false;
        },
        sync: function (method, model, options) {
            var currentMethod = method.toString().toUpperCase();
            if (currentMethod == 'DELETE') {
                options.url = '/Roles/DeleteRole/' + model.id;
            } else if (currentMethod == "CREATE" || currentMethod == "UPDATE") {
                options.url = '/Roles/UpdateRole/' + model.id;
            }
            return Backbone.sync(method, model, options);
        },
        initialize: function () {
            this.bind("change:RoleName", function () {
                var roleName = this.get('RoleName');
                this.set({ RoleName: roleName });
            });
        },
        defaults: {
            RoleId: '',
            RoleName: '',
            RoleDisplayName: '',
            Description: ''
        },
        validateModel: function () {
            var validate = true;
            var divHtml = "<div class='ui-state-error ui-corner-all' style='display: block; padding-top: 0px; padding-bottom: 0px; width: 500px; padding-left: 0.7em; padding-right: 0.7em;'>";
            divHtml += "<p><span class='ui-icon ui-icon-alert' style='float: left; margin-right: .3em;'></span><strong>Please correct these Errors</strong> </p><div class='validation-summary-errors' data-valmsg-summary='true'>";
            divHtml += "</div><p></p></div>";
            var ulHtml = "<ul></ul>";
            var div = $(divHtml);
            var ul = $(ulHtml);
            if (this.get('RoleName') == "") {
                ul.append("<li>Bắt buộc nhập ký hiệu</li>");
                validate = false;
            }
            if (this.get('RoleDisplayName') == "") {
                ul.append("<li>Bắt buộc nhập tên vai trò</li>");
                validate = false;
            }
            div.find(".validation-summary-errors").append(ul);

            if (!validate) {
                $('#valSum').show("slow");
                $('#valSum').html(div);
            }
            else {
                $('#valSum').hide("slow");
                $('#valSum').html("");
            }

            return validate;
        }
    });

    // Role Collection
    var RoleCollection = Backbone.Collection.extend({
        model: Role,
        url: '/Roles/GetList/?nocache='+ (new Date()).toJSON()
    });

    // User Collection
    var UserCollection = Backbone.Collection.extend({
        model: User,
        url: '/Roles/GetUserList/?nocache='+ (new Date()).toJSON()
    });
    //Role-Edit view
    var EditView = Backbone.View.extend({
        template: _.template($('#Role-Edit-Template').html()),
        tagName: "table",
        container: "#Role_Edit",
        initialize: function () {
        },
        events: {
            "change .gName": 'NameChange',
            "change .gDisp": 'DispChange',
            "change .gDesc": 'DescChange',
            "click .Update": 'UpdateRole',
            "click .Cancel": 'CancelRoler'
        },
        NameChange: function () {
            // Directly bind the name change to the model, best use of back bone.
            // Otherwise set the data during save which ever you prefer
            this.model.set({ RoleName: $(".gName").val() });
        },
        DispChange: function () {
            this.model.set({ RoleDisplayName: $(".gDisp").val() });
        },
        DescChange: function () {
            this.model.set({ Description: $(".gDesc").val() });
        },
        render: function () {
            $(this.container).append($(this.el).html(this.template(this.model.toJSON())));
            $("input:button", $(this.el)).button();
            var self = this;
            $("#RoleEditDialog").bind("dialogclose", function (event, ui) {
                self.unrender();
            });
            $("#RoleEditDialog").dialog("open");

            var title = 'Thêm vai trò';
            if (this.collection == null)
                title = 'Sửa vai trò - ' + this.model.get('RoleName');
            $(this.container).find('legend').html(title);
            $('#valSum').hide("slow");
            return this;
        },
        unrender: function () {
            $(this.el).remove();
            return this;
        },
        UpdateRole: function () {
            if (this.model.validateModel()) {
                var self = this;
                if (this.collection != null) {
                    this.collection.add(this.model);
                }
                this.model.save(this.model, {
                    success: function () {
                        self.unrender();
                        $("#RoleEditDialog").dialog("close");
                        var roleName = self.model.get('RoleName');
                        $("input:button", '#Role_List').button();
                    }
                });
            }
            $("input:button", '#Role_List').button();
        },
        CancelRoler: function () {
            this.model.fetch({
                success: function () {
                    $("input:button", '#Role_List').button();
                }
            });
            this.unrender();
            $("#RoleEditDialog").dialog("close");
        }
    });

    // Role Delete View
    var DeleteView = Backbone.View.extend({
        template: _.template($('#Role-Delete-Template').html()),
        container: "#Role_Edit",
        initialize: function () {

        },
        events: {
            "click .Update": 'DeleteRole',
            "click .Cancel": 'CancelRole'
        },
        render: function () {
            $(this.container).append($(this.el).html(this.template(this.model.toJSON())));
            $("input:button", $(this.el)).button();
            $("#RoleEditDialog").dialog("option", "height", 200);
            $("#RoleEditDialog").dialog("open");
            var title = 'Xóa vai trò - ' + this.model.get('RoleName');
            $(this.container).find('legend').html(title);
            return this;
        },
        unrender: function () {
            $(this.el).remove();
            return this;
        },
        CancelRole: function () {
            this.unrender();
            $("#RoleEditDialog").dialog("close");
        },
        DeleteRole: function () {
            var self = this;
            this.model.destroy({
                success: function () {
                    self.unrender();
                    $("#RoleEditDialog").dialog("close");
                }
            });
        }
    });

    // Genre View - el returns the template enclosed within a tr
    var RoleView = Backbone.View.extend({
        template: _.template($('#Role-Template').html()),
        tagName: "tr",
        initialize: function () {
            this.model.bind('change', this.render, this);
            this.model.bind('remove', this.unrender, this);
            this.collection = new UserCollection();
            this.collection.on('reset', this.loadUsers, this);
        },
        render: function () {
            $(this.el).html(this.template(this.model.toJSON()));
            return this;
        },
        unrender: function () {
            $(this.el).remove();
            return this;
        },
        events: {
            "click .UserList": 'GetUsers',
            "click .Edit": 'EditRole',
            "click .Delete": 'DeleteRole'
        },
        GetUsers: function () {
            this.collection.fetch({
                data: {
                    Id: this.model.get('RoleName')
                }
            });
        },
        loadUsers: function () {
            var self = this;
            this.users = $('#UserList');
            this.users.append('<tr><th></th><th>Tên đăng nhập</th></tr>');
            this.collection.each(function (user) {
                var item = new UserItem({
                    model: user
                });
                self.users.append(item.el);
            });
            //$('.chkAll').bind('change', { collection: self.collection }, self.selectAllUser);

            //$('.chkitem').bind('change', function () {
            //    $('.chkAll').attr('checked', $('.chkitem:checked').length == $('.chkitem').length);
            //});
            this.users.append('<tr><td colspan="2"><input type="button" value="Cập nhật" class="Update" /> | <input type="button" id="btnCancel" value="Hủy" class="Cancel" /></td></tr>');

            this.users.find('.Update').bind('click', function () {
                var selectedUsers = [];
                _.each(self.collection.models, function (item) {
                    selectedUsers.push(item.toJSON());
                });
                $.post('/roles/AssignUser', { 'id': self.model.get('RoleName'), 'collection': JSON.stringify( selectedUsers)}, function (data) {
                });
                self.users.empty();
                $("#UserListDialog").dialog('close');
            });
            this.users.find('.Cancel').bind('click', function () {
                self.users.empty();
                $("#UserListDialog").dialog('close');
            });
            $("input:button", '#UserList').button();
            $("#UserListDialog").bind("dialogclose", function (event, ui) {
                self.users.empty();
            });
            $("#UserListDialog").dialog('open');
        },
        EditRole: function () {
            var editView = new EditView({ model: this.model });
            editView.render();
        },
        DeleteRole: function () {
            var deleteView = new DeleteView({ model: this.model });
            deleteView.render();
        }
    });
    // user item
    var UserItem = Backbone.View.extend({
        tagName: 'tr',
        events: {
            'change .chkitem': 'CheckItem'
        },
        CheckItem: function (event) {
            var $target = $(event.currentTarget);
            this.model.set({ 'IsInRole': $target.is(":checked") == true });
        },
        initialize: function () {
            this.model.bind('remove', this.unrender, this);
            this.template = _.template($('#user-template').html());
            this.render();
        },
        render: function () {
            var html = this.template(this.model.toJSON());
            this.$el.html(html);
        },
        unrender: function () {
            $(this.el).remove();
            return this;
        }
    });
    // Actual App view
    var AppView = Backbone.View.extend({
        initialize: function () {
            this.collection.bind('add', this.AppendRole, this);
        },
        el: '#Role_Container',
        events: {
            "click #btnCreateNew": "AddNewRole"
        },
        AddNewRole: function () {
            var newRole = new Role();
            var editView = new EditView({ model: newRole, collection: this.collection });
            editView.render();
        },
        AppendRole: function (role) {
            var roleView = new RoleView({ model: role });
            $(this.el).find('#Role_List').append(roleView.render().el);
        },
        render: function () {
            if (this.collection.length > 0) {
                this.collection.each(this.AppendRole, this);
            }
            $("input:button", "#Role_List").button();
        }
    });
    var roles = new RoleCollection();
    var view = new AppView({ collection: roles });

    roles.fetch({
        success: function () {
            view.render();
        }
    });
});
